package com.jc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class PostgreSQLTransaction {
    public static void main(String[] args) {
        String url = null;
        String user = null;
        String password = null;
        String insertSql = "insert into users(name, created_at) values(?, ?)";
        String updateSql = "update users set name = ? where id = ?";

        // 读取配置文件（适配资源目录）
        try (InputStream file = PostgreSQLTransaction.class.getClassLoader().getResourceAsStream("db.properties")) {
            if (file == null) {
                System.out.println("错误：未找到 db.properties 文件");
                return;
            }
            Properties p = new Properties();
            p.load(file);
            url = p.getProperty("url");
            user = p.getProperty("user");
            password = p.getProperty("password");
        } catch (IOException e) {
            System.out.println("配置文件读取失败：" + e.getMessage());
            return;
        }

        // 校验配置
        if (url == null || user == null || password == null) {
            System.out.println("错误：db.properties 配置不完整");
            return;
        }

        // 注册驱动
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("错误：未找到 PostgreSQL 驱动");
            return;
        }

        // 执行事务
        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            conn.setAutoCommit(false); // 关闭自动提交，开启事务

            try (PreparedStatement insertPs = conn.prepareStatement(insertSql);
                 PreparedStatement updatePs = conn.prepareStatement(updateSql)) {

                // 插入操作
                insertPs.setString(1, "anne");
                insertPs.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
                insertPs.executeUpdate();

                // 更新操作
                updatePs.setString(1, "anne");
                updatePs.setInt(2, 2);
                updatePs.executeUpdate();

                // 所有操作成功，提交事务
                conn.commit();
                System.out.println("事务提交成功！");

            } catch (SQLException e) {
                // 任一操作失败，回滚事务
                conn.rollback();
                System.out.println("事务执行失败：" + e.getMessage());
                System.out.println("错误码：" + e.getErrorCode());
                System.out.println("事务已回滚");
            }

        } catch (SQLException e) {
            System.out.println("数据库连接失败：" + e.getMessage());
        }
    }
}